<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\MyLog;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

require_once 'AipSpeech.php';
require_once('function.php');
require_once('moban.php');

class IndexController extends Controller
{

//录音识别接口
    public function voiceUpload(Request $request)
    {

        //获取传递的红包id和openid
        $redid = $request->redid;
        $openid = $request->openid;
        $duration = $request->duration;
        if ($redid == '' || $openid == '') {
            echo 'not' ;exit;
        }
        $Path = "/public/voiceUpload/";
        if (!empty($_FILES['file'])) {
            //获取扩展名
            $exename = $this->getExeName($_FILES['file']['name']);
            $fileName = base_path() . $Path;//文件路径
            $savename = 'voice_' . date("YmdHis") . rand(0, 100);
            $upload_name =  $savename . '.' . $exename;//文件名加后缀
            if (!file_exists($fileName)) {
                //进行文件创建
                mkdir($fileName, 0777, true);
            }
            $imageSavePath = $fileName . $upload_name;
            if (move_uploaded_file($_FILES['file']['tmp_name'], $imageSavePath)) {
                $imgPath = $Path . $upload_name;
                //文件转码
                $cmd2 = "/monchickey/ffmpeg/bin/ffmpeg -y  -i /www/wwwroot/huwai/kxred/public/voiceUpload/".$upload_name."  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 /www/wwwroot/huwai/kxred/public/voiceUpload/".$savename.".pcm" ;
                exec($cmd2,$log,$status);
                //转码成功，语音识别
                if ($status == 0) {
                    // //讯飞api
                    // $appid = '5a5ea94a';
                    // $voice = file_get_contents('./Uploads/333.pcm');
                    // $CurTime = time();
                    // $info = base64_encode($voice);
                    // $checkSum = MD5('95d4e153aab5470ba2478b47dbb4fd26'.$CurTime.'eyJhdWUiOiJyYXciLCJhdWYiOiIxNksiLCJzY2VuZSI6Im1haW4ifQ=='.'data='.$info);
                    // $data = 'data='.$info;
                    // $head = [
                    //     'appid' => $appid,
                    //     'time' => $CurTime,
                    //     'param' => 'eyJhdWUiOiJyYXciLCJhdWYiOiIxNksiLCJzY2VuZSI6Im1haW4ifQ==',
                    //     'checkSum' => $checkSum
                    // ];
                    // $res = http_xunfei('http://api.xfyun.cn/v1/aiui/v1/iat',$data,'xunfei',$head);
                    // echo $res;

                    //百度api
                    $client = new \AipSpeech('10682414', 'oNQk3m81WIj0ie9YHh7II9GG', '1ZZXELN2run6zA5GCFzGCGskTUI4AG4K');
                    $get = $client->asr(file_get_contents('./voiceUpload/'.$savename.'.pcm'), 'pcm', 16000, array(
                        'lan' => 'zh',
                    ));
                    @unlink('./voiceUpload/'.$savename.'.pcm');//删除pcm文件
                    if (isset($get["result"])) { //识别成功，开始匹配
                        $inf = DB::table('redf')->where([['id','=',$redid],['sign','=',1],['status','=',1]])->first();
                         if ($inf->s_number == 0 || $inf->s_price == 0 || !$inf ) {//剩余红包数量为0
                                echo '1000' ;exit;
                            }
                        $password = $inf->password;
                        $word = mb_substr($get["result"][0],0,-1);
                        $a = pinyin($password);
                        $b = pinyin($word);
                        //返回相似度
                        similar_text($a,$b,$sim);
                        // echo $a.'-'.$b.'-'.$sim;exit;
                        //匹配度大于78%，匹配成功,返回随机金额，并存进数据库
                        if ($sim > 80 && $inf->s_number==1 && $inf->pay_type == 0) { //剩余红包为1，发送模板消息
                            //开启事务
                            DB::beginTransaction();
                            try{
                                $info = DB::table('redf')->where([['id','=',$redid],['sign','=',1],['status','=',1]])->lockForUpdate()->first();
                                 if ($info->s_number == 0 || $info->s_price == 0 || !$info ) {//剩余红包数量为0
                                        DB::commit();
                                        echo '1000' ;exit;
                                    }
                                 //获得金额
                                $money = $this->getRandomMoney((int)$info->s_number,(float)$info->s_price,$redid);
                                //添加收红包记录
                                $insert = [
                                    'fid' => $redid,
                                    'openid' =>$openid,
                                    'price' =>$money,
                                    'duration' =>$duration,
                                    'voice_url' =>'https://hd.huwaishequ.com/kxred/public/voiceUpload/'.$upload_name,
                                    'sign' => 1,
                                    'created_at' => time(),
                                ];
                                $in1 = DB::table('reds')->insert($insert);
                                //加入个人钱包
                                $in2 = DB::table('wallet')->where('openid',$openid)->increment('money',$money);
                                if ($in1 && $in2 && $money) {
                                     DB::commit();
                                      //返回给前台
                                    $select = DB::table('user')->select('username','head_ico','gender')->where('open_id',$openid)->first();
                                    $arr = [
                                        'username' => $select->username,
                                        'head_ico' => $select->head_ico,
                                        'gender' => $select->gender,
                                        'price' => $money,
                                        'duration' =>$duration,
                                        'voice_url' => 'https://hd.huwaishequ.com/kxred/public/voiceUpload/'.$upload_name,
                                        'created_at' => time(),
                                    ];
                                    $pre = DB::table('cdorder')->where([['order_sn','=',$info->order_sn],['sign','=',1]])->first();
                                    //发送模板消息
                                    $moban = new \Moban();
                                    $htime = secToTime(time()-$info->created_at);
                                    $mobanData = [
                                        'keyword1' => ['value'=>'语音口令\''.$info->password.'\''],
                                        'keyword2' => ['value'=> $htime.'被抢光'],
                                        'keyword3' => ['value'=>'点击此处去看看吧']
                                     ];
                                    $ttt = $moban->send($info->openid,'tM5F0WOaFmzvtS26Ytx38d8uYkzSyZuPORf6cpMjiAU','pages/voice_box/parcel_detail/index?id='.$redid,$pre->prepay_id,$mobanData);
                                    //将回调数据写入日志
                                    $mylog = new MyLog;
                                    $redata = '[redid]'.$redid.'[openid]'.$info->openid.'[err]'.$ttt->errmsg;
                                    $mylog->setLog('语音模板数据:'.$redata,$logPath='moban(yuyin)');
                                    echo json_encode($arr) ;exit;
                                }
                            }catch (\Exception $e){
                                DB::rollBack();
                                //匹配失败
                                @unlink('./voiceUpload/'.$upload_name);//删除mp3文件
                                 //将回调数据写入日志
                                $mylog = new MyLog;
                                $redata = '[redid]'.$redid.'[openid]'.$openid.'[err]'.$e;
                                $mylog->setLog('领取红包错误数据:'.$redata,$logPath='hongbao');
                                echo '1001';exit;
                            }
                        }else if($sim > 80){ //不发送模板消息
                            //开启事务
                            DB::beginTransaction();
                            try{
                                $info = DB::table('redf')->where([['id','=',$redid],['sign','=',1],['status','=',1]])->lockForUpdate()->first();
                                 if ($info->s_number == 0 || $info->s_price == 0 || !$info ) {//剩余红包数量为0
                                        DB::commit();
                                        echo '1000' ;exit;
                                    }
                                  //获得金额
                                    $money = $this->getRandomMoney((int)$info->s_number,(float)$info->s_price,$redid);
                                    //添加收红包记录
                                    $insert = [
                                        'fid' => $redid,
                                        'openid' =>$openid,
                                        'price' =>$money,
                                        'duration' =>$duration,
                                        'voice_url' =>'https://hd.huwaishequ.com/kxred/public/voiceUpload/'.$upload_name,
                                        'sign' => 1,
                                        'created_at' => time(),
                                    ];
                                    $in1 = DB::table('reds')->insert($insert);
                                    //加入个人钱包
                                    $in2 = DB::table('wallet')->where('openid',$openid)->increment('money',$money);
                                    if ($in1 && $in2 && $money) {
                                        DB::commit();
                                         //返回给前台
                                        $select = DB::table('user')->select('username','head_ico','gender')->where('open_id',$openid)->first();

                                        $arr = [
                                            'username' => $select->username,
                                            'head_ico' => $select->head_ico,
                                            'gender' => $select->gender,
                                            'price' => $money,
                                            'duration' =>$duration,
                                            'voice_url' => 'https://hd.huwaishequ.com/kxred/public/voiceUpload/'.$upload_name,
                                            'created_at' => time(),
                                        ];

                                        echo json_encode($arr) ;exit;
                                    }
                            }catch (\Exception $e){
                                DB::rollBack();
                                //匹配失败
                                @unlink('./voiceUpload/'.$upload_name);//删除mp3文件
                                  //将回调数据写入日志
                                $mylog = new MyLog;
                                $redata = '[redid]'.$redid.'[openid]'.$openid.'[err]'.$e;
                                $mylog->setLog('领取红包错误数据:'.$redata,$logPath='hongbao');
                                echo '1001';exit;
                            }
                        }
                    //匹配失败
                        @unlink('./voiceUpload/'.$upload_name);//删除mp3文件
                        echo '1001';exit;
                    }
                    //识别失败，提示重新录音
                        @unlink('./voiceUpload/'.$upload_name);//删除mp3文件
                        echo '1001';exit;
                }
                    //转码失败，提示系统繁忙
                        @unlink('./voiceUpload/'.$upload_name);//删除mp3文件
                        echo '1002';exit;
            }
                    //文件上传失败，提示系统繁忙
                        echo '1002';exit;
        }
    }

 //语音加载接口
    public function voiceLoad(Request $request){
        //获取发红包id
        $redid = $request->redid;
        $openid = $request->openid;
        $code_url = 'https://hd.huwaishequ.com/kxred/public/wxcode/wx'.$redid.'.png';
        if ($redid == '' || $openid == '') {
            echo 'not';exit;
        }
        $flag = false;
        $money = '';
        $where = [
            ['id','=',$redid],
            ['status','=',1],
            ['sign','=',1]
        ];
        $data = DB::table('redf')->select('uid','password','price','number','s_number','created_at','s_price','is_return')->where($where)->first();//红包数据
        if (!$data) {//页面不存在或未生效
            echo 'notallow';exit;
        }
        $udata = DB::table('user')->select('username','head_ico')->where('id',$data->uid)->first();//用户数据
        $vdata = DB::table('reds')->select('user.username','user.head_ico','user.gender','reds.price','reds.voice_url','reds.created_at','reds.openid','reds.duration')
                                  ->leftJoin('user', 'reds.openid', '=', 'user.open_id')
                                  ->where([['reds.fid','=',$redid],['reds.sign','=',1]])
                                  ->orderBy('reds.created_at', 'desc')
                                  ->get();//录音数据
        $created_at = $data->created_at;
        $is_return = $data->is_return;
        foreach ($vdata as $value) {
            if ($value->openid == $openid) {
                $flag = true;
                $money = $value->price;
                break;
            }
        }
        //组合有用数据
        if ($flag) { //已经领取了
             $arr = [
                'data' => $data,
                'udata' => $udata,
                'vdata' => $vdata,
                'open_mouse' => 2,
                'getback' => 0,
                'cashbox' => $money,
                 'code_url' => $code_url
             ];
        }else if ($data->s_number == 0) {//红包数量为0
            $arr = [
                'data' => $data,
                'udata' => $udata,
                'vdata' => $vdata,
                'open_mouse' => 3,
                'getback' => 0,
                'cashbox' => '',
                'code_url' => $code_url
            ];
        }else if ($created_at +86300 < time() || $is_return == 1) {//已经过期48小时,退回剩余
            $arr = [
                'data' => $data,
                'udata' => $udata,
                'vdata' => $vdata,
                'open_mouse' => 1,
                'getback' => $data->s_price,
                'cashbox' => '',
             ];
        }else{ //可以领取
            $arr = [
                'data' => $data,
                'udata' => $udata,
                'vdata' => $vdata,
                'open_mouse' => 0,
                'getback' => 0,
                'cashbox' => '',
                'code_url' => $code_url
            ];
        }
        echo json_encode($arr);exit;
    }


 /*
  * 我收到的红包
  * */
    public function myReds(Request $request){
        if($request->openid){
//            $reds_key = 'key_' . Input::get('page');
//            if (Cache::has($reds_key)) {
//                return Cache::get($reds_key);//读取
//            }
            $reds = DB::table('reds')->select('reds.price','user.head_ico','reds.created_at','reds.fid','user.username')
                ->leftJoin('redf', 'reds.fid', '=', 'redf.id')
                ->leftJoin('user', 'redf.openid', '=', 'user.open_id')
                ->where([['reds.openid','=',$request->openid],['reds.sign','=',1],['redf.status','=',1]])
                ->orderBy('reds.created_at', 'desc')
                ->paginate(5);
            foreach ($reds as $key => $value){
                $value->created_at = date("Y-m-d H:i:s", $value->created_at);
                $value->price = number_format($value->price,2, '.', '');
            }

            $sum = number_format(DB::table('reds')->where([['openid','=',$request->openid],['sign','=',1]])->sum('price'),2, '.', '');//求和
            $redsList_value = ['redsList' => $reds,'sum'=>$sum];

            //加入到缓存
            //Cache::put($reds_key, $redsList_value, 1);
            //return Cache::get($reds_key);//读取

            return $redsList_value;
        }else{
            return "参数错误！";
        }
    }

    /*
     * 我发出的红包
     * */

    public function myRedf(Request $request){

        if($request->openid){

            $redf = DB::table('redf')->select('id','price','number','s_number','password','created_at')
                 ->where([['openid','=',$request->openid],['status','=',1],['sign','=',1]])
                ->orderBy('redf.created_at', 'desc')->paginate(5);
            foreach ($redf as $key => $value){
                $value->created_at = date("Y-m-d H:i:s", $value->created_at);
                $value->price = number_format($value->price,2, '.', '');

            }

           $sum = number_format(DB::table('redf')->where([['openid','=',$request->openid],['status','=',1],['sign','=',1]])->where('status',1)->sum('price'),2, '.', '');//求和
            $redfList_value = ['redfList' => $redf,'sum'=>$sum];

            return $redfList_value;
        }else{
            return "参数错误！";
        }
    }





    //获取文件后缀名
    public function getExeName($fileName)
    {
        $pathinfo = pathinfo($fileName);
        return strtolower($pathinfo['extension']);
    }

    //获取随机红包
    public function getRandomMoney($remainSize,$remainMoney,$id) {
     // $remainSize 剩余的红包数量
     // $remainMoney 剩余的钱
    if ($remainSize == 1) {
             $res = DB::table('redf')->where([['id','=',$id],['sign','=',1],['status','=',1]])->decrement('s_number',1,['s_price' => 0]);//数据库红包数量减一
             // DB::table('redf')->where('id',$id)->update(['s_price'=>0]);//剩余金额
             if ($res) {
                return round($remainMoney * 100) / 100;
             }
                return false;
         }
         $min   = 0.01;
         $max   = $remainMoney / $remainSize * 2;
         $money = $this->randFloat() * $max;
         $money = $money <= $min ? 0.01: $money;
         $money = floor($money * 100) / 100;
         $a = DB::table('redf')->where([['id','=',$id],['sign','=',1],['status','=',1]])->decrement('s_number',1);//数据库红包数量减一
         $b = DB::table('redf')->where([['id','=',$id],['sign','=',1],['status','=',1]])->decrement('s_price', $money);//剩余金额
         if ($a && $b) {
            return $money;
         }
            return false;
    }

    //0-1的随机数
    public function randFloat($min=0, $max=1){
        if ($min + mt_rand()/mt_getrandmax() * ($max-$min) == 1) {
            return $min + mt_rand()/mt_getrandmax() * ($max-$min);
        }
        return $min + mt_rand()/mt_getrandmax() * ($max-$min);
    }



}